package com.xbongbong.dingtalkPay.service.impl;

import com.alibaba.dingtalk.openapi.helper.AuthHelper;
import com.alibaba.dingtalk.openapi.helper.Env;
import com.alibaba.dingtalk.openapi.helper.ServiceHelper;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.request.OapiAppstoreInternalOrderConsumeRequest;
import com.dingtalk.api.request.OapiAppstoreInternalOrderFinishRequest;
import com.dingtalk.api.request.OapiAppstoreInternalOrderGetRequest;
import com.dingtalk.api.request.OapiAppstoreInternalSkupageGetRequest;
import com.dingtalk.api.request.OapiAppstoreInternalUnfinishedorderListRequest;
import com.dingtalk.api.response.OapiAppstoreInternalOrderConsumeResponse;
import com.dingtalk.api.response.OapiAppstoreInternalOrderFinishResponse;
import com.dingtalk.api.response.OapiAppstoreInternalOrderGetResponse;
import com.dingtalk.api.response.OapiAppstoreInternalSkupageGetResponse;
import com.dingtalk.api.response.OapiAppstoreInternalUnfinishedorderListResponse;
import com.taobao.api.ApiException;
import com.xbongbong.dingtalkPay.service.DingtalkPayHttpService;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.helper.PageHelper;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.pro.dingtalkPay.pojo.dto.GetOrderInfoDTO;
import com.xbongbong.pro.dingtalkPay.pojo.dto.OrderConsumeDTO;
import com.xbongbong.pro.dingtalkPay.pojo.dto.OrderFinishDTO;
import com.xbongbong.pro.dingtalkPay.pojo.dto.SkupageGetDTO;
import com.xbongbong.pro.dingtalkPay.pojo.dto.UnfinishedOrderListDTO;
import com.xbongbong.pro.dingtalkPay.pojo.vo.GetOrderInfoVO;
import com.xbongbong.pro.dingtalkPay.pojo.vo.OrderConsumeVO;
import com.xbongbong.pro.dingtalkPay.pojo.vo.OrderFinishVO;
import com.xbongbong.pro.dingtalkPay.pojo.vo.SkupageGetVO;
import com.xbongbong.pro.dingtalkPay.pojo.vo.UnfinishedOrderListVO;
import com.xbongbong.pro.dingtalkPay.pojo.vo.UnfinishedOrderVO;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.saas.constant.dingtalk.DingtalkPayHttpConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @version v1.0
 * @desc 钉钉共创内购http服务实现类
 * @auther: youli.chen
 * @date: 2019-9-26
 * @since v1.0
 */
@Service("dingtalkPayHttpService")
public class DingtalkPayHttpServiceImpl implements DingtalkPayHttpService {

    private static final Logger LOG = LoggerFactory.getLogger(DingtalkPayHttpServiceImpl.class);

    @Resource
    private AuthHelper authHelper;


    private String getAccessToken(String corpId){
        String accessToken = null;
        try {
            accessToken = authHelper.getAccessToken(corpId);
        } catch (Exception e) {
            LOG.error("获取accessToken失败", e);
        }
        return accessToken;
    }

    /**
     * 获取内购商品SKU页面地址
     *
     * @param skupageGetDTO
     */
    @Override
    public SkupageGetVO getSkuPage(SkupageGetDTO skupageGetDTO) throws XbbException {
        String getSkuPageUrl = DingtalkPayHttpConstant.DINGTALK_PAY_URL + DingtalkPayHttpConstant.GET_SKU_PAGE;
        DefaultDingTalkClient client = new DefaultDingTalkClient(getSkuPageUrl);
        OapiAppstoreInternalSkupageGetRequest request = new OapiAppstoreInternalSkupageGetRequest();
        request.setGoodsCode(skupageGetDTO.getGoodsCode());
        request.setCallbackPage(skupageGetDTO.getCallbackPage());
        request.setHttpMethod("GET");
        String accessToken = getAccessToken(skupageGetDTO.getCorpid());
        OapiAppstoreInternalSkupageGetResponse response = null;
        try {
            response = client.execute(request, accessToken);
        } catch (ApiException e) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018, response.getErrmsg());
        }
        SkupageGetVO skupageGetVO = new SkupageGetVO();
        skupageGetVO.setUrl(response.getResult());
        return skupageGetVO;
    }

    /**
     * 内购商品订单处理完成
     *
     * @param orderFinishDTO
     * @return
     * @throws ApiException
     */
    @Override
    public OrderFinishVO orderFinish(OrderFinishDTO orderFinishDTO) throws XbbException {
        String orderFinishUrl = DingtalkPayHttpConstant.DINGTALK_PAY_URL + DingtalkPayHttpConstant.ORDER_FINISH;
        DefaultDingTalkClient client = new DefaultDingTalkClient(orderFinishUrl);
        OapiAppstoreInternalOrderFinishRequest request = new OapiAppstoreInternalOrderFinishRequest();
        request.setBizOrderId(orderFinishDTO.getOrderId());
        String accessToken = getAccessToken(orderFinishDTO.getCorpid());
        OapiAppstoreInternalOrderFinishResponse response = null;
        try {
            response = client.execute(request, accessToken);
        } catch (ApiException e) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018, response.getErrmsg());
        }
        OrderFinishVO orderFinishVO = new OrderFinishVO();
        orderFinishVO.setOrderCode(response.getErrcode());
        orderFinishVO.setOrderMsg(response.getErrmsg());
        return orderFinishVO;
    }

    /**
     * 获取内购订单信息
     *
     * @param getOrderInfoDTO
     * @return
     * @throws ApiException
     */
    @Override
    public GetOrderInfoVO getOrder(GetOrderInfoDTO getOrderInfoDTO) throws XbbException {
        String getOrderUrl = DingtalkPayHttpConstant.DINGTALK_PAY_URL + DingtalkPayHttpConstant.GET_ORDER;
        DefaultDingTalkClient client = new DefaultDingTalkClient(getOrderUrl);
        OapiAppstoreInternalOrderGetRequest request = new OapiAppstoreInternalOrderGetRequest();
        request.setBizOrderId(getOrderInfoDTO.getOrderId());
        request.setHttpMethod("GET");
        String accessToken = getAccessToken(getOrderInfoDTO.getCorpid());
        OapiAppstoreInternalOrderGetResponse response = null;
        try {
            response = client.execute(request, accessToken);
        } catch (ApiException e) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018, response.getErrmsg());
        }
        OapiAppstoreInternalOrderGetResponse.InAppGoodsOrderVo inAppGoodsOrderVo = response.getResult();
        GetOrderInfoVO getOrderInfoVO = new GetOrderInfoVO();
        BeanUtil.copyProperties(inAppGoodsOrderVo, getOrderInfoVO);
        Long createTimestamp = inAppGoodsOrderVo.getCreateTimestamp();
        Long startTimestamp = inAppGoodsOrderVo.getStartTimestamp();
        Long endTimestamp = inAppGoodsOrderVo.getEndTimestamp();
        Long paidTimestamp = inAppGoodsOrderVo.getPaidTimestamp();
        if(createTimestamp != null){
            getOrderInfoVO.setCreateTime(DateUtil.getString(createTimestamp, DateUtil.SDF));
        }
        if(startTimestamp != null){
            getOrderInfoVO.setStartTime(DateUtil.getString(startTimestamp, DateUtil.SDF));
        }
        if(endTimestamp != null){
            getOrderInfoVO.setEndTime(DateUtil.getString(endTimestamp, DateUtil.SDF));
        }
        if(paidTimestamp != null){
            getOrderInfoVO.setPaidTime(DateUtil.getString(paidTimestamp, DateUtil.SDF));
        }
        // 实际支付总金额，单位为分(RMB)
        Long totalActualPayFee = inAppGoodsOrderVo.getTotalActualPayFee();
        if(totalActualPayFee != null){
            // 实际支付总金额，单位为元(RMB)
            getOrderInfoVO.setTotalActualPayFee(Double.valueOf(totalActualPayFee/100));
        }

        return getOrderInfoVO;
    }

    /**
     * 应用内购商品核销
     *
     * @param orderConsumeDTO
     * @return
     * @throws ApiException
     */
    @Override
    public OrderConsumeVO orderConsume(OrderConsumeDTO orderConsumeDTO) throws XbbException {
        String orderConsumeUrl = DingtalkPayHttpConstant.DINGTALK_PAY_URL + DingtalkPayHttpConstant.ORDER_CONSUME;
        DefaultDingTalkClient client = new DefaultDingTalkClient(orderConsumeUrl);
        OapiAppstoreInternalOrderConsumeRequest request = new OapiAppstoreInternalOrderConsumeRequest();
        request.setBizOrderId(orderConsumeDTO.getOrderId());
        request.setQuantity(orderConsumeDTO.getQuantity());
        request.setRequestId(getUUID());
        request.setUserid(orderConsumeDTO.getUserId());
        String accessToken = getAccessToken(orderConsumeDTO.getCorpid());
        OapiAppstoreInternalOrderConsumeResponse response = null;
        try {
            response = client.execute(request, accessToken);
        } catch (ApiException e) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018, response.getErrmsg());
        }
        OrderConsumeVO orderConsumeVO = new OrderConsumeVO();
        orderConsumeVO.setOrderConsumeCode(response.getErrorCode());
        orderConsumeVO.setOrderConsumeMsg(response.getErrmsg());
        return orderConsumeVO;
    }

    /**
     * 获取未处理的已支付订单
     *
     * @param unfinishedOrderListDTO
     * @return
     * @throws ApiException
     */
    @Override
    public UnfinishedOrderListVO getUnfinishedOrderList(UnfinishedOrderListDTO unfinishedOrderListDTO) throws XbbException {
        Long page = unfinishedOrderListDTO.getPage();
        Long pageSize = unfinishedOrderListDTO.getPageSize();
        if(pageSize > 100L){
            // 分页查询每页大小，最大限制100
            unfinishedOrderListDTO.setPageSize(100L);
        }
        OapiAppstoreInternalUnfinishedorderListRequest request = new OapiAppstoreInternalUnfinishedorderListRequest();
        request.setItemCode(unfinishedOrderListDTO.getItemCode());
        request.setPage(page);
        request.setPageSize(pageSize);
        request.setHttpMethod("GET");
        String getUnfinishedOrderListUrl = DingtalkPayHttpConstant.DINGTALK_PAY_URL + DingtalkPayHttpConstant.GET_UNFINISHED_ORDER_LIST;
        DefaultDingTalkClient client = new DefaultDingTalkClient(getUnfinishedOrderListUrl);
        String suiteAccessToken = ServiceHelper.getSuiteToken(Env.SUITE_KEY, Env.SUITE_SECRET, Env.suiteTicket);
        OapiAppstoreInternalUnfinishedorderListResponse response = null;
        try {
            response = client.execute(request, suiteAccessToken);
        } catch (ApiException e) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018, response.getErrmsg());
        }
        UnfinishedOrderListVO unfinishedOrderListVO = new UnfinishedOrderListVO();
        List<UnfinishedOrderVO> unfinishedOrderVOList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if(response.getResult() != null){
            List<OapiAppstoreInternalUnfinishedorderListResponse.InAppGoodsOrderVO> items = response.getResult().getItems();
            for (OapiAppstoreInternalUnfinishedorderListResponse.InAppGoodsOrderVO inAppGoodsOrderVO : items) {
                UnfinishedOrderVO unfinishedOrderVO = new UnfinishedOrderVO();
                BeanUtil.copyProperties(inAppGoodsOrderVO, unfinishedOrderVO);
                Long createTimestamp = inAppGoodsOrderVO.getCreateTimestamp();
                Long paidTimestamp = inAppGoodsOrderVO.getPaidTimestamp();
                if(createTimestamp != null){
                    unfinishedOrderVO.setCreateTime(DateUtil.getString(createTimestamp, DateUtil.SDF));
                }
                if(paidTimestamp != null){
                    unfinishedOrderVO.setPaidTime(DateUtil.getString(paidTimestamp, DateUtil.SDF));
                }
                // 实际支付总金额，单位为分(RMB)
                Long totalActualPayFee = inAppGoodsOrderVO.getTotalActualPayFee();
                if(totalActualPayFee != null){
                    // 实际支付总金额，单位为元(RMB)
                    unfinishedOrderVO.setTotalActualPayFee(Double.valueOf(totalActualPayFee/100));
                }
                unfinishedOrderVOList.add(unfinishedOrderVO);
            }
        }
        PageHelper pageHelper = new PageHelper(page.intValue(), pageSize.intValue());
        if (unfinishedOrderVOList != null) {
            pageHelper.setRowsCount(unfinishedOrderVOList.size());
        }
        unfinishedOrderListVO.setList(unfinishedOrderVOList);
        unfinishedOrderListVO.setPageHelper(pageHelper);
        return unfinishedOrderListVO;
    }

    /**
     * 获取uuid,去掉中间的"-"
     * @return
     * kaka
     * 2017年3月21日 下午5:21:27
     */
    private String getUUID() {
        String uuid = UUID.randomUUID().toString();
        // 去掉“-”符号
        return uuid.replaceAll("-", "");
    }

}
